<script setup>
import { ref, computed } from 'vue'
import { getCurrentUserService, updateCurrentUserService, fileUploadService } from '@/api/common'
import { imageUrlToFile } from '@/utils/request'
import UserPasswordUpdate from './components/UserPasswordUpdate.vue'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'

const router = useRouter()

// 下拉刷新
const refreshLoading = ref(false)

// 获取用户id
const userStore = useUserStore()
const userId = userStore.user.id

// 用户信息
const userInfo = ref({
  id: userId, // 当前登录用户id
  username: null, // 用户名
  name: null, // 姓名
  gender: null, // 性别
  age: null, // 年龄
  mobilePhone: null, // 移动电话
  idNumber: null, // 身份证号码
  email: null, // 电子邮件
  address: null, // 地址
  avatarUrl: null // 头像链接
})

// 获取当前用户信息
const getCurrentUser = async () => {
  const res = await getCurrentUserService()
  const { data } = res.data
  userInfo.value = {
    id: userId,
    username: data.username,
    name: data.name,
    gender: data.gender,
    age: data.age,
    mobilePhone: data.mobilePhone,
    idNumber: data.idNumber,
    email: data.email,
    address: data.address,
    avatarUrl: data.avatarUrl
  }
  refreshLoading.value = false
}
getCurrentUser()

// 提交处理
const handleSubmit = async () => {
  if (imgInfo.value.name) {
    // 将网络图片地址转换为file对象
    const file = await imageUrlToFile(imgInfo.value.url, imgInfo.value.name)
    const res = await fileUploadService(file)
    userInfo.value.avatarUrl = res.data.data
  }
  await updateCurrentUserService(userInfo.value)
  imgInfo.value = {
    name: '',
    url: ''
  }
  showNotify({
    type: 'success',
    message: '修改成功'
  })
  router.back()
}

// 取消处理
const handleCancel = () => {
  router.back()
}

// 头像上传
const imgInfo = ref({
  name: '', // 文件名
  url: '' // 网络图片地址
})
const getImageUrl = (uploadFile) => {
  imgInfo.value.name = uploadFile.file.name
  imgInfo.value.url = uploadFile.objectUrl // 预览图片
}

// 头像删除处理
const handleDeleteAvatar = () => {
  userInfo.value.avatarUrl = null
  imgInfo.value = {
    name: '',
    url: ''
  }
}

// 转换上传文件列表（用于双向绑定）
const fileList = computed({
  get: () => {
    if (userInfo.value.avatarUrl) {
      return [{ url: userInfo.value.avatarUrl, isImage: true }]
    } else if (imgInfo.value.url) {
      return [{ url: imgInfo.value.url, isImage: true }]
    } else {
      return []
    }
  },
  set: (newList) => {
    if (newList.length === 0) userInfo.value.avatarUrl = null
  }
})

// 修改密码
const passwordUpdateRef = ref()
const handleUpdatePassword = () => {
  passwordUpdateRef.value.open()
}
</script>

<template>
  <div class="user-info">
    <van-nav-bar
      title="个人资料"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
      right-text="修改密码"
      @click-right="handleUpdatePassword"
      fixed
    />
    <van-pull-refresh v-model="refreshLoading" @refresh="getCurrentUser" success-text="加载成功">
      <van-form class="form-container" @submit="handleSubmit">
        <van-field
          v-model="userInfo.username"
          name="username"
          label="用户名"
          placeholder="请输入用户名"
        />
        <van-field name="avatarUrl" label="头像">
          <template #input>
            <van-uploader
              v-model="fileList"
              :max-count="1"
              :after-read="getImageUrl"
              @delete="handleDeleteAvatar"
              accept="image/*"
              preview-size="80px"
              upload-icon="plus"
              upload-text="上传头像"
            >
            </van-uploader>
          </template>
        </van-field>
        <van-field v-model="userInfo.name" name="name" label="姓名" placeholder="请输入姓名" />
        <van-field name="gender" label="性别">
          <template #input>
            <van-radio-group v-model="userInfo.gender" direction="horizontal">
              <van-radio name="男">男</van-radio>
              <van-radio name="女">女</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field name="stepper" label="年龄">
          <template #input>
            <van-stepper v-model="userInfo.age" min="0" max="127" integer />
          </template>
        </van-field>
        <van-field
          v-model="userInfo.mobilePhone"
          name="mobile"
          label="移动电话"
          placeholder="请输入移动电话"
        />
        <van-field
          v-model="userInfo.idNumber"
          name="idNumber"
          label="身份证号"
          placeholder="请输入身份证号码"
        />
        <van-field
          v-model="userInfo.email"
          name="email"
          label="电子邮箱"
          placeholder="请输入电子邮箱"
        />
        <van-field
          v-model="userInfo.address"
          rows="1"
          autosize
          label="地址"
          type="textarea"
          placeholder="请输入地址"
        />
        <div class="button-group">
          <van-button round block type="primary" native-type="submit">提交</van-button>
          <van-button round block plain type="default" @click="handleCancel">取消</van-button>
        </div>
      </van-form>
    </van-pull-refresh>
    <!-- 余额充值弹出层 -->
    <user-password-update ref="passwordUpdateRef"></user-password-update>
  </div>
</template>

<style lang="scss" scoped>
.user-info {
  padding-top: 46px;
  background-color: #f7f8fa;
  min-height: 100vh;

  .form-container {
    padding: 16px;

    .van-field {
      margin-bottom: 12px;
      background: white;
      border-radius: 8px;
      padding: 12px 16px;
    }

    .button-group {
      margin-top: 24px;
      display: flex;
      gap: 16px;

      .van-button {
        flex: 1;
      }
    }
  }
}
</style>
